package cn.virens.common.easyexcel;

import cn.virens.common.util.core.Assert;
import cn.virens.common.util.exception.APIException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@SuppressWarnings("serial")
public class ExcelImportExecutorManage extends ConcurrentHashMap<String, ExcelImportExecutor<?>> {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 添加任务
     */
    public <T extends ExcelImportExecutor<?>> T addTask(T executor) throws APIException {
        ExcelImportExecutor<?> lastExecutor = get(executor.getTaskUuid());
        if (lastExecutor == null || lastExecutor.isComplete()) {
            this.put(executor.getTaskUuid(), executor);

            executor.setComplete(this::complete);

            return executor;
        }

        return null;
    }

    private Map<String, Object> toMap(ExcelImportExecutor<?> executor) {
        Map<String, Object> answer = new HashMap<>();

        answer.put("taskTime", executor.getTaskTime());
        answer.put("taskUuid", executor.getTaskUuid());
        answer.put("complete", executor.isComplete());
        answer.put("error", executor.getError());
        answer.put("size", executor.getSize());

        return answer;
    }

    /**
     * 获取任务详情
     */
    public Map<String, Object> getTask(ExcelImportExecutor<?> executor) {
        return getTask(executor.getTaskUuid());
    }

    /**
     * 获取任务信息
     */
    public Map<String, Object> getTask(String key) throws APIException {
        ExcelImportExecutor<?> currExecutor = get(Assert.isEmpty(key));
        if (currExecutor == null || currExecutor.isComplete()) {
            if (currExecutor != null && remove(key) != null) {
                return toMap(currExecutor);
            }

            return Map.of("complete", true);
        }

        return toMap(currExecutor);
    }

    private void complete(List<?> list) throws APIException {
        logger.debug("导入完成：" + list.size());
    }
}
